import { Module, MiddlewareConsumer, RequestMethod } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';
import { APP_INTERCEPTOR } from '@nestjs/core';
import { AppConfigModule } from '@/modules/config.module';
import { AppConfigService } from '@/common/config.service';
import { HttpLoggingMiddleware } from '@/middleware/http-logging.middleware';
import { TraceIdMiddleware } from '@/middleware/trace-id.middleware';
import { ResponseInterceptor } from '@/common/interceptors/response.interceptor';
import { User } from '@/entities/user.entity';
import { AuthController } from '@/controllers/auth.controller';
import { HealthController } from '@/controllers/health.controller';
import { RedisController } from '@/controllers/redis.controller';
import { UsersController } from '@/controllers/users.controller';
import { ExampleController } from '@/controllers/example.controller';
import { AuthService } from '@/services/auth.service';
import { UsersService } from '@/services/users.service';
import { JwtStrategy } from '@/strategies/jwt.strategy';
import { JwtAuthGuard } from '@/guards/jwt-auth.guard';
import { CommonModule } from '@/modules/common.module';
import { SequenceDemoController } from '@/controllers/sequence-demo.controller';
import { SequenceController } from '@/controllers/sequence.controller';

@Module({
    imports: [
        // 配置模块 - 根据环境自动加载 JSON 配置文件
        AppConfigModule,

        // 数据库模块
        TypeOrmModule.forRootAsync({
            imports: [AppConfigModule],
            useFactory: (configService: AppConfigService) => ({
                type: 'mysql',
                host: configService.getDatabaseConfig().host,
                port: configService.getDatabaseConfig().port,
                username: configService.getDatabaseConfig().username,
                password: configService.getDatabaseConfig().password,
                database: configService.getDatabaseConfig().database,
                entities: [__dirname + '/**/*.entity{.ts,.js}'],
                synchronize: configService.getDatabaseConfig().synchronize,
                logging: configService.getDatabaseConfig().logging,
                dropSchema: configService.getDatabaseConfig().dropSchema,
            }),
            inject: [AppConfigService],
        }),

        // 实体模块
        TypeOrmModule.forFeature([User]),

        // JWT模块
        JwtModule.registerAsync({
            imports: [AppConfigModule],
            useFactory: (configService: AppConfigService) => ({
                secret: configService.getJwtConfig().secret,
                signOptions: {
                    expiresIn: configService.getJwtConfig().expiresIn,
                },
            }),
            inject: [AppConfigService],
        }),

        // Passport模块
        PassportModule,

        // 通用模块（包含logging、redis、sequence）
        CommonModule,
    ],
    controllers: [AuthController, HealthController, RedisController, UsersController, ExampleController, SequenceController, SequenceDemoController],
    providers: [
        AuthService,
        UsersService,
        JwtStrategy,
        JwtAuthGuard,
        {
            provide: APP_INTERCEPTOR,
            useClass: ResponseInterceptor,
        },
    ],
})
export class AppModule {
    configure(consumer: MiddlewareConsumer) {
        consumer.apply(TraceIdMiddleware, HttpLoggingMiddleware).forRoutes({ path: '*', method: RequestMethod.ALL });
    }
}
